<?php


namespace app\api\controller;

use app\admin\model\UserRecord;
use app\common\controller\Api;
use app\admin\model\CashOut;
use app\admin\model\Goods;
use app\admin\model\User;
use think\Validate;
use think\Db;

class Cash extends Api
{
    //protected $noNeedLogin = ['*'];
    protected $noNeedLogin = ['eailVerification','authentication', 'cashOut'];
    protected $noNeedRight = ['*'];

    /**
     * 邮箱身份验证
     *
     * @param int $uid  用户id
     * @param string $email 邮箱
     */
    public function eailVerification()
    {
        $this->checkParam(['email']);
        //$this->checkParam('token', 'head');
        /*$token = $this->request->header('token');
        $user = Token::get($token);*/
        $uid = $this->auth->id;
        //$uid = 1;
        $user = User::where('id', $uid)->find();
        $email = $this->request->param('email');
        if ($email && !Validate::is($email, "email")) {
            $this->error(__('Email is incorrect'));
        }
        User::where('id',$user['id'])->update(['email' => $email]);
        //防止订单号重复
        do{
            $ordersn = create_order_code();
            $order= CashOut::where('ordersn', $ordersn)->find();
        }while(!empty($order));
        $paypal = CashOut::where('user_id', $user['id'])->where('type',2)->find();
        //判断是否有过申请身份验证记录
        if ($paypal) {
            $this->error(__('You have applied for authentication'));
        }
        $data = [
            'ordersn' => $ordersn,
            'user_id' => $user['id'],
            'app_id' => $user['app_id'],
            'type' => 2,
            'price' => 0.04,
            'email' => $email,
            'addtime' => date('Y-m-d H:i:s',time())
        ];
        CashOut::insert($data);
        $this->success(__('successful'));
    }

    /**
     * 身份验证
     *
     * @param int $uid  用户id
     * @param decimal $amount 金额
     */
    public function authentication()
    {
        $this->checkParam(['amount']);
        //$this->checkParam('token', 'head');
        //$token = $this->request->header('token');
        //$user = Token::get($token);
        $uid = $this->auth->id;
        //$uid = 1;
        $user = User::where('id', $uid)->find();
        $amount = $this->request->param('amount');
        $paypal = CashOut::where('user_id', $user['id'])->where('type',2)->find();
        //是否已经验证通过
        if ($paypal['status'] == 1 && $user['paypal'] == 1) {
            $this->success(__('You are authenticated'));
        }
        $time = date('Y-m-d H:i:s',time());
        $paypal_time = $user['paypaltime'] ? strtotime($user['paypaltime']) : 0;
        //判断是否第三次验证失败，联系三次则1小时后才能再次验证
        if ($user['error_num'] % 3 == 0 && $paypal_time + 3600 > time()) {
            $this->error(__('Pause verification. Please try again later'), ['time' => $paypal_time + 3600 - time()]);
        }
        if ($amount == $paypal['price']) {
            //验证正确
            CashOut::where('ordersn', $paypal['ordersn'])->update(['status' => 1, 'updatetime' => $time]);
            User::where('id',$user['id'])->update(['paypal' => 1, 'paypaltime' => $time]);
            $this->success(__('Verification successful'));
        } else {
            //验证错误
            User::where('id',$user['id'])->update(['error_num' => $user['error_num'] + 1, 'paypaltime' => $time]);
            //判断是否第三次验证失败，联系三次则1小时后才能再次验证
            if (($user['error_num'] + 1) % 3 == 0 && $paypal_time + 3600 > $time) {
                $this->error(__('Pause verification. Please try again later'), ['time' => $paypal_time + 3600 - time()]);
            }
            $this->error(__('Validation failed'));
        }


         /*dump($this->request->param());*/

    }

    /**
     * 提现
     *
     * @param int $uid  用户id
     * @param int $goods 商品id
     */
    public function cashOut()
    {
        $this->checkParam(['goods_id']);
        /*$this->checkParam('token', 'head');
        $token = $this->request->header('token');*/
        $uid = $this->auth->id;
        //$uid = 1;
        $user = User::where('id', $uid)->find();

        $goods_id = $this->request->param('goods_id');
        $goods = Goods::where('id', $goods_id)->find();
        if (!$goods) {
            $this->error(__('The product does not exist'));
        }
        $email = $this->request->param('email');

        $currency = $goods['paytype'] == 0 ? 'dollar' : 'coin';

        Db::startTrans();

        $res = $this->updateUserAccount($uid, 4, 1,[$currency => $goods['price'], 'card' => $goods['card']]);
        if ($res['status']) {
            do{
                $ordersn = create_order_code();
                $order= CashOut::where('ordersn', $ordersn)->find();
            }while(!empty($order));
            $data = [
                'ordersn' => $ordersn,
                'user_id' => $user['id'],
                'app_id' => $user['app_id'],
                'type' => $goods['paytype'],
                'price' => $goods['price'],
                'email' => $user['email'],
                'goods_sku' => $goods['sku'],
                'email' => $email,
                'addtime' => date('Y-m-d H:i:s',time())
            ];
            $id = CashOut::insertGetId($data);

            Db::commit();
            $data = Db::table('sdk_cash_out')
                ->alias('sco')
                ->field('sg.*, sco.*')
                ->join('sdk_goods sg','sco.goods_sku = sg.sku')
                ->where('sco.id', $id)
                ->find();
            $data['arrival_time'] = date('Y-m-d H:i:s',strtotime($data['addtime'])+3600*72);
            //dump($data);die;
            $this->success(__('Cash withdrawal has been applied, please wait for processing'), $data);
        } else {
            Db::rollback();
            $this->error(__($res['msg']));
        }


       /* //判断用户美元是否足够
        if ($goods['paytype'] == 0 && $user['dollar'] < $goods['price']) {
            $this->error(__('The dollar is not enough'));
        }
        //判断用户金币是否足够
        if ($goods['paytype'] == 0 && $user['coin'] < $goods['price']) {
            $this->error(__('The coin is not enough'));
        }
        //判断用户金提现卡是否足够
        if ($user['card'] < $goods['card']) {
            $this->error(__('The Withdrawal card is not enough'));
        }*/



        /*dump($this->request->param());*/
    }

    protected function updateUserAccount($uid, $action, $type, $array, $ext=null) {
        $change = $type == 0 ? '+' : '-';
        $change_type = $type == 0 ? 0 : 1;
        $user = User::where('id', $uid)->lock(true)->find();
        if (!$user) {
            return array('status' => false, 'msg' => 'Account error');
        }
        $msg = [
            'coin' => 'Insufficient gold coins',
            'dollar' => 'The dollar is not enough',
            'card' => 'Insufficient withdrawal card'
        ];
        $type = [
            'dollar' => 0,
            'coin' => 1,
            'card' => 2
        ];
        $data = [
            'user_id' => $uid,
            'app_id' => $user['app_id'],
            'action' => $action,
            'change_type' => $change_type,
            'addtime' => date('Y-m-d H:i:s',time()),
            'ext' => $ext
        ];

        foreach ($array as $k => $v) {
            if ($v) {
                $data['type'] = $type[$k];
                if ($change == '-' && $v > $user[$k]) {
                    return array('status' => false, 'msg' => $msg[$k]);
                }
                $data['change_before'] = $user[$k];
                $data['change'] = $change . $v;
                $data['num'] = $v;
                $data['change_after'] = $user[$k] + $data['change'];
                User::where('id',$uid)->update([$k => $data['change_after']]);
                UserRecord::insert($data);
            }
        }
        return array('status' => true);
    }

}